package com.wrx.redis_learning.utils;

import lombok.extern.slf4j.Slf4j;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import java.util.concurrent.CompletableFuture;
/**
 * @author wrx
 * 2024/06/03
 */
@Slf4j
public class EmailSendUtil {
    private static final String host = "smtp.qq.com";
    private static final String port = "587";
    private static final String username = "2329627258@qq.com";
    private static final String password = "dxezqdsrjseqeaih";

    /**
     * 发送邮件，进行邮箱验证
     * param target 用户的 email
     */
    public static void  sendEmail(String target,String topic,String content){
        Properties props = new Properties(); // 创建一个配置类
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", host); // 你的邮件服务器主机名
        props.put("mail.smtp.port", port); // SMTP端口号，一般为587
        // 获取会话对象，需要验证发件人的身份
        Session session = Session.getInstance(props,
            new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });
        try {
            // 创建一封邮件
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(username)); // 这是发件人
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(target)); //这是收件人
            message.setSubject(topic); // 设置邮件主题
            message.setText(content); // 设置邮件内容
            // 发送邮件
            Transport.send(message);
            log.info("邮件发送成功");
        } catch (MessagingException e) {
            log.info("邮件发送失败");
            e.printStackTrace();
        }
    }
    /**
     * 异步 操作 发送 邮件
     * @param target 目标邮箱
     * @param topic 邮件主题
     * @param content 邮件内容
     */
    public static void sendEmailAsync(String target, String topic, String content) {
        CompletableFuture.runAsync(() -> sendEmail(target, topic, content));
    }
}
